<?php
namespace app\common\controller;
trait Task{
	protected $tasking='tasking';// 未完成任务表名称
	protected $tasked='tasked';// 已完成任务表名称

	/**
	 * 创建任务
	 * @param  array  $data 基本任务数据如下：
	 * [
	 * 'member_id'=>'任务发布人ID'
	 * 'title'=>'标题'，
	 * 'msg'=>'一些信息',
	 * 'device'=>'需要发送指令的设备ID json字符串 空值代表所有',
	 * 'interval'=>'操作间隔频率 单位：s',
	 * 'options'=>'额外参数',
	 * 'media_id'=>'多媒体表的id（通常存贮图片、音频等）',
	 * 'source_id'=>'素材库表ID（通常该任务是通过发送素材库内容等）',
	 * 'event'=>'指令（必选项）',
	 * 'action'=>'动作（指令细分 默认：0）',
	 * 'type'=>'类型（0：完成后存贮记录 1：不存贮（例：切换任务等简单任务））'
	 * ]
	 * @param  int  $member_id 用户ID
	 */
    function createTask($data=[],$member_id,$files=[],$callback=null){
    	if(!isset($data['event'])){
    		return error(lang('Instruction event does not exist'));
    	};
    	$data['s_time']=time();
        if(isset($data['dev']))$data['device']=json_encode($data['dev'],JSON_UNESCAPED_UNICODE);
        if(isset($data['software']))$data['software']=json_encode($data['software'],JSON_UNESCAPED_UNICODE);

		// if(isset($data['software'])){ //账号分身ID
  //           $software=model('software')->readAll(['id'=>['id','in',$data['software']]],0,['field'=>'body_id']);
  //           $s=[];
  //           foreach ($software as $v) {
  //               $s[]=$v['body_id'];
  //           }
  //           $data['software']=json_encode($s,JSON_UNESCAPED_UNICODE);
  //       }

        if(isset($data['social'])){ //好友昵称或者备注
            $social=model('social')->readAll(['id'=>['id','in',$data['social']]],0,['field'=>'name']);
            $s=[];
            foreach ($social as $v) {
                $s[]=$v['name'];
            }
            $data['social']=json_encode($s,JSON_UNESCAPED_UNICODE);
        }
    	if(isset($data['options']))$data['options']=json_encode($data['options'],JSON_UNESCAPED_UNICODE);

        $add=model($this->tasking)->add($data);
		// 额外添加的操作 用于添加任务附件
		if(!empty($add)&&!empty($files)){
			$taskMedia=[];
            foreach ($files as $v) {
                $taskMedia[]=[
                    'task_id'=>$add['id'],
                    'media_id'=>$v,
                ];
            }
			if(!empty($taskMedia)){ // 关联图片
                model('taskMedia')->add($taskMedia);
            }
        }
        if(!is_null($callback)&&is_callable($callback)){
            call_user_func($callback,$add['id']);
            return $add['id'];
        }
        $isExecute=false;
        if(is_bool($callback)){
            $isExecute=$callback;
        }
		// 执行定时 或者 加入队列
		return model($this->tasking)->runTask($add['id'],$isExecute);
    }
    /**
     * 构建任务数据(结合$this->createTask()可创建任务)
     * @param  array   $post post数据
     * @param  integer $uid  用户ID
     * @return array
     */
    protected function getTaskData($post,$uid){
    	// 关联设备
    	$dev=isset($post['dev'])&&!empty($post['dev'])?$post['dev']:[];
        if(empty($dev)&&isset($post['device'])){
            $dev=$post['device'];
        }
        $software=isset($post['software'])&&!empty($post['software'])?$post['software']:[];
        $social=isset($post['social'])&&!empty($post['social'])?$post['social']:[];
    	if(isset($post['dev_group'])){ // 用户选择了分组
    	    $devs=model('group_device')->readAll(['group_id'=>['group_id','in',$post['dev_group']]],0,['field'=>'relation_id']);
    	    foreach ($devs as $v) {
    	        if(!in_array($v['relation_id'], $dev)){
    	            array_push($dev,$v['relation_id']);
    	        }
    	    }
    	}
        if(is_string($dev)){
            $dev=json_decode($dev,true);
        }
        if(is_array($dev)){
        	$dev=array_unique($dev); //去除重复
        }

    	$options=[
    		'friends'=>isset($post['qz1'])?1:0, // 发送好友
    		'group'=>isset($post['qz2'])?1:0, // 发送群组
    		'interval'=>isset($post['interval'])?(int)$post['interval']:0, // 发送间隔
    		'sex'=>isset($post['sex'])?$post['sex']:0, // 性别筛选 0：女 1：男 2：所有
    		'number'=>isset($post['number'])&&!empty($post['number'])?explode('|',$post['number']):[],
            'count'=>isset($post['count'])?$post['count']:5, 
            'limit'=>isset($post['limit'])?$post['limit']:5,
            'offset'=>isset($post['offset'])?$post['offset']:0, 
            'index'=>isset($post['index'])?$post['index']:0, 
    		'indexEnd'=>isset($post['indexEnd'])?$post['indexEnd']:0, 
            'sign'=>isset($post['sign'])&&!empty($post['sign'])?explode('|',$post['sign']):[],
            'msg'=>isset($post['msg'])&&!empty($post['msg'])?explode('|',$post['msg']):[],
    		'nickname'=>isset($post['nickname'])?explode('|',$post['nickname']):[],
            'city'=>isset($post['city'])?$post['city']:'', // 城市（定位使用）
    		'address'=>isset($post['address'])?$post['address']:'', // 详细的地址（定位使用）
    		'lng'=>isset($post['lng'])?$post['lng']:'', //经度
    		'lat'=>isset($post['lat'])?$post['lat']:'', //纬度
    	];
        $runtime=isset($post['runtime'])?$post['runtime']:'';
        if(!empty($options['lng'])&&!empty($options['lat'])){
            $mac=getMAC($options['lat'],$options['lng']);
            $mnc=getMAC($options['lat'],$options['lng'],'mnc');
            $options['rewifi']=$mac;
            $options['recell']=$mnc;
        }
    	$data=[
    		'member_id'=>$uid,
    		'options'=>$options,
    		'event'=>$post['event'],
    		'action'=>$post['action'],
    		'title'=>$post['title'],
    		'msg'=>isset($post['msg'])?$post['msg']:[],//此处的信息是单行的
            'dev'=>$dev, // 设备ID组
            'software'=>$software, // 账号ID组
    		'social'=>$social, // 好友ID组
    		
    		'loop'=>isset($post['loop'])?$post['loop']:0, // 是否循环请求
    		'runtime'=>$runtime, // 循环执行时间
    		'source_id'=>isset($post['source_id'])?$post['source_id']:'', //素材ID
    		'type'=>$post['type'], //完成任务后是否删除 0：存贮 1删除
    		'remark'=>$post['remark'], //任务说名
    	];

    	// 是循环任务 并且 没有设置循环执行时间时给予默认值
    	if($data['loop']&&empty($data['runtime'])){
    	    $data['runtime']='00:00:00';
    	}
    	// 执行时间 立即执行选项优先级 最高
    	$nowstart=isset($post['nowstart'])?$post['nowstart']:0;
        if(is_string($nowstart)){
            $nowstart=$nowstart=='true';
        }
    	$starttime=isset($post['starttime'])?$post['starttime']:'';
        $time=time();
    	if(!$nowstart&&!empty($starttime)){
    	    $data['start_time']=strtotime($starttime.' '.$data['runtime']);
    	}elseif($nowstart){
    	    $data['loop']=0;
            $data['runtime']='';
    	    $data['start_time']=$time;
    	}
    	
    	if(empty($data['start_time'])||$data['start_time']==0){
    	    $data['start_time']=$time;
    	}
        if(is_string($data['loop'])){
            $data['loop']=$data['loop']=='true';
        }
        if(!$data['loop']){ //非循环任务
            $data['status']=1;
        }
    	return $data;
    }
}
